import React, { memo, useEffect, useRef, useState } from 'react'
import { Editor, Toolbar } from '@wangeditor/editor-for-react'
import type { IDomEditor, IEditorConfig, IToolbarConfig } from '@wangeditor/editor'

import '@wangeditor/editor/dist/css/style.css' // 引入 css
import styles from './index.module.scss'

const toolbarConfig: Partial<IToolbarConfig> = {
  toolbarKeys: [
    'bold',
    // 'italic',
    'color',
    'header2',
    'header3',
    'bulletedList',
    'numberedList',
    // 'justifyLeft',
    // 'justifyRight',
    'clearStyle',
    'fullScreen',
  ],
}

function MyEditor(props: any) {
  const [editor, setEditor] = useState<IDomEditor | null>(null) // 存储 editor 实例
  // const editor = useRef<IDomEditor | null>()
  // 及时销毁 editor ，重要！
  useEffect(() => {
    return () => {
      if (editor == null)
        return
      editor?.destroy()
    }
  }, [])

  const onChange = (e: any) => {
    if (e.getText()) {
      props.onChange(e.getHtml())
    }
    else {
      props.onChange('')
    }
  }
  useEffect(() => {
    if (props.value && editor) {
      let html = ''
      if (props.value.trim()[0] === '<') {
        html = `<>${props.value}</>`
      }
      else {
        html = `<div>${props.value}</div>`
      }

      editor?.setHtml(html)
    }
  }, [props.value, editor])

  function onCreated(e: any) {
    setEditor(e)
    // editor.current = e
  }
  let html = ''

  if (props.value) {
    if (props.value.trim()[0] === '<') {
      html = `<>${props.value}</>`
    }
    else {
      html = `<div>${props.value}</div>`
    }
  }
  else {
    html = `<>${props.value}</>`
  }
  const editorConfig: Partial<IEditorConfig> = {
    placeholder: '请输入内容...',
    autoFocus: false,
    onCreated,
    onChange,
  }
  return (
    <div className={styles.editor}>
      <Toolbar
        editor={editor}
        defaultConfig={toolbarConfig}
        mode="simple"
        style={{
          borderBottom: '1px solid #f5f2f0',
          position: props.titleFiexd ? 'fixed' : '',
          top: 0,
          left: 0,
          width: '100%',
          zIndex: 100,
        }}
      />
      {
        <Editor
          defaultConfig={editorConfig}
          mode="simple"
          style={
            props.titleFiexd
              ? { paddingTop: '40px', height: '300px', overflowY: 'hidden' }
              : { height: '300px', overflowY: 'hidden' }
          }
        />
      }
    </div>
  )
}

export default memo(MyEditor, (o, n) => {
  return o.value === n.value
})
